﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using Nomad.WebSync.Extensions;

namespace Nomad.WebSync.Windows.Pages {
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : Page {
        public Login() {
            InitializeComponent();
        }

        private void executeLogin() {
            using (var service = new WebSyncService.Desktop()) {
                var result = service.Login(usernameTextBox.Text, passwordTextBox.Password.Encrypt());
                if (string.IsNullOrEmpty(result))
                    throw new Exception("Invalid Login");

                App.WebSyncHeader = new WebSyncService.WebSyncHeader();
                App.WebSyncHeader.Session = result;                
            }

            using (var service = Services.Desktop.Connect()) {
                App.OwnerName = service.GetOwnerName();
            }

            NavigationService.Navigate(new Pages.Today());
        }
        private void cancelLogin() {
            App.Current.Shutdown();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.usernameTextBox.Focus();
            } catch (Exception ex) {
                MessageBox.Show(ex.SoapMessage(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
        private void cancelButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.cancelLogin();
            } catch (Exception ex) {
                MessageBox.Show(ex.SoapMessage(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
        private void loginButton_Click(object sender, RoutedEventArgs e) {
            this.Cursor = Cursors.Wait;
            try {
                this.executeLogin();
            } catch (Exception ex) {
                MessageBox.Show(ex.SoapMessage(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                this.Cursor = Cursors.Arrow;
            }
        }
    }
}
